package com.pig4cloud.pigx.contract.feign;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import com.pig4cloud.pigx.contract.api.feign.ContractPositionFeign;
import com.pig4cloud.pigx.contract.entity.ContractPosition;
import com.pig4cloud.pigx.contract.enums.ContractPositionEnum;
import com.pig4cloud.pigx.contract.executer.order.supporter.OrderCalculator;
import com.pig4cloud.pigx.contract.mapper.ContractPositionMapper;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;

/**
 * 合约-仓位 feign接口实现
 *
 */
@RestController
@AllArgsConstructor
@Api(value = "contract-position")
@RequestMapping("/contract-position")
public class ContractPositionFeignImpl implements ContractPositionFeign {

	private final ContractPositionMapper contractPositionMapper;
	private final RedisTemplate redis;

	/**
	 * 根据用户id 获取用户的未实现盈亏（USDT-精度2位）
	 *
	 * @param userId 用户id
	 * @return {@link R< BigDecimal>}
	 * @since 2022/9/13 22:20
	 */
	@Inner
	@Override
	@PostMapping(FLOAT_PROFIT_BY_USER)
	public R<BigDecimal> getFloatProfitByUser(@Validated @RequestBody @NotNull(message = "数据异常，userId为空") Long userId,
											  @RequestHeader(SecurityConstants.FROM) String from) {

		// 查询所有当前仓位币对名称、开仓均价、开仓数量
		QueryWrapper<ContractPosition> query = new QueryWrapper<>();
		query.lambda()
				.select(ContractPosition::getSymbolName,
						ContractPosition::getSide,
						ContractPosition::getOpenAvgPrice,
						ContractPosition::getNowNum
				)
				.eq(ContractPosition::getUserId, userId)
				.in(ContractPosition::getStatus,
						ContractPositionEnum.Status.OPEN.getValue(),
						ContractPositionEnum.Status.PARTIAL_CLOSE.getValue(),
						ContractPositionEnum.Status.LIQUIDATING.getValue());

		List<ContractPosition> list = contractPositionMapper.selectList(query);

		BigDecimal totalProfit = BigDecimal.ZERO;
		for (ContractPosition i : list) {
			// 获取标记价
			String markRedisKey = i.getSymbolName() + "_mark_price";
			Object markPrice = redis.opsForValue().get(markRedisKey);
			if (Objects.isNull(markPrice)) {
				continue;
			}
//			if (i.getCloseNum() != null) {
//				i.setOpenNum(i.getOpenNum().subtract(i.getCloseNum()));
//			}
			// 计算盈亏
			BigDecimal profit = OrderCalculator.getProfit((BigDecimal) markPrice, i.getOpenAvgPrice(), i.getNowNum(), i.getSide());
			// 累计总盈亏
			totalProfit = totalProfit.add(profit);
		}

		// 处理精度
		totalProfit = totalProfit.setScale(2, RoundingMode.HALF_UP);

		return R.ok(totalProfit);
	}
}
